import { AppServiceBase, Http, IParams, LogUtil } from "ibiz-core";
import { getCookie, setCookie } from "qx-util";

/**
 * 应用权限类
 *
 * @export
 * @class AppAuthService
 */
export class AppAuthService {

    /**
     * 唯一实例
     * 
     * @private
     * @static
     * @memberof AppAuthService
     */
    private static readonly instance = new AppAuthService();

    /**
     * 获取唯一实例
     *
     * @static
     * @return {*}  {AppAuthService}
     * @memberof AppAuthService
     */
    public static getInstance(): AppAuthService {
        return AppAuthService.instance;
    }

    /**
     * 用户登录
     *
     * @memberof AppAuthService
     */
    public async login(loginForm: IParams) {
        const post: any = await Http.getInstance().post('/v7/login', loginForm, true);
        const { status, data } = post;
        if (status == 200) {
            this.setExpiredDate(new Date(data.expirdate));
        }
        return post;
    }

    /**
     * 刷新token
     *
     * @public
     * @param {*} [data={}]
     * @memberof AppAuthService
     */
    public async refreshToken(data: any = {}) {
        if (data && ((data.url == "/v7/refreshToken") || (data.url == "/v7/login") || (data.url == "/appdata") || data.url.startsWith('./assets'))) {
            return true;
        }
        try {
            const response = await Http.getInstance().get('/v7/refreshToken');
            if (response && response.status === 200) {
                const data = response.data;
                this.setExpiredDate(new Date(data.expirdate));
                if (data) {
                    setCookie('ibzuaa-token', data.token, 7, true);
                }
                return true;
            } else {
                LogUtil.log("刷新token出错");
                return false;
            }
        } catch (error) {
            return false;
        }
    }

    /**
     * 是否过期
     *
     * @public
     * @param {Date} [date]
     * @memberof AppAuthService
     */
    public isExpired(date: Date): boolean {
        const environment = AppServiceBase.getInstance().getAppEnvironment();
        if (this.getExpiredDate()) {
            if(environment){
                return date.getTime() > ((this.getExpiredDate() as Date).getTime() - environment.refreshTokenTime);
            }else{
                return false;
            }
        } else {
            // this.setExpiredDate(new Date());
            return false;
        }
    }

    /**
     * 获取过期时间
     *
     * @memberof AppAuthService
     */
    public getExpiredDate() {
        const expiredTime = getCookie('ibzuaa-expired');
        if(expiredTime){
            return new Date(Number(expiredTime));
        }else{
            return null;
        }
    }

    /**
     * 设置过期时间
     *
     * @memberof AppAuthService
     */
    public setExpiredDate(date: Date) {
        setCookie('ibzuaa-expired', date.getTime().toString(), 7, true);
    }

}

